﻿<script type="text/javascript">
    $('span.headingText').html('Role');

    var worksListModel = false;
    $(document).ready(function () {
        onLoadWorksPage();
        loadGrid();
    });
    function onLoadWorksPage() {
        $('#worksForm').submit(function (e) {
            onSubmitInventory();
            return false;
        });

    }

    function executePreCondition() {
        // trim field vales before process.
        trimFormValues($("#worksForm"));

        if ($("#worksForm").validate({ onfocusout: false }).form() == false) {
            return false;
        }
        return true;
    }

    function onSubmitInventory() {
        if (executePreCondition() == false) {
            return false;
        }

        setButtonDisabled($('.save'), true);
        showLoadingSpinner(true);
        var actionUrl = null;
        if ($('#id').val().isEmpty()) {
            actionUrl = "${createLink(controller:'invItem', action: 'createWork')}";
        } else {
            actionUrl = "${createLink(controller: 'invItem', action: 'updateWork')}";
        }

        jQuery.ajax({
            type: 'post',
            data: jQuery("#worksForm").serialize(),
            url: actionUrl,
            success: function (data, textStatus) {
                executePostCondition(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            },
            complete: function (XMLHttpRequest, textStatus) {
                setButtonDisabled($('.save'), false);
                showLoadingSpinner(false);
            },
            dataType: 'json'
        });
        return false;
    }


    function executePostCondition(result) {
        if (result.isError) {
            showConstraintsErrors($(result.errors));
            showLoadingSpinner(false);
        } else {
            try {
                var newEntry = result.works;
                if ($('#id').val().isEmpty() && newEntry.entity != null) { // newly created

                    var previousTotal = parseInt(worksListModel.total);
                    var firstSerial = 1;

                    if (worksListModel.rows.length > 0) {
                        firstSerial = worksListModel.rows[0].cell[0];
                        regenerateSerial($(worksListModel.rows), 0);
                    }
                    newEntry.entity.cell[0] = firstSerial;

                    worksListModel.rows.splice(0, 0, newEntry.entity);

                    if ($('#flex1').countEqualsResultPerPage(previousTotal)) {
                        worksListModel.rows.pop();
                    }

                    worksListModel.total = ++previousTotal;
                    $("#flex1").flexAddData(worksListModel);

                } else if (newEntry.entity != null) { // updated existing
                    updateListModel(worksListModel, newEntry.entity, 0);
                    $("#flex1").flexAddData(worksListModel);
                }

                resetForm();
                showSuccess(result.message);

            } catch (e) {
                // Do Nothing
            }
        }
    }

    function resetForm() {
        clearForm($("#worksForm"));
        $('#create').attr('value', 'Create');
        $('#name').focus();
    }

    function loadGrid() {
        $("#flex1").flexigrid
            (
                    {
                        url: false,
                        dataType: 'json',
                        colModel: [
                            { display: "OID", name: "OID", width: 30, sortable: false, align: "right", hide: true },
                            { display: "Name", name: "Name", width: 120, sortable: false, align: "left"},
                            { display: "Mobile No", name: "MobileNo", width: 100, sortable: true, align: "left" },
                            { display: "Email", name: "email", width: 100, sortable: true, align: "left" }
                        ],
                        buttons: [
                            { name: 'Edit', bclass: 'edit', onpress: selectWorks },
                            { name: 'Delete', bclass: 'delete', onpress: deleteWorks },
                            { name: 'Clear Results', bclass: 'clear-results', onpress: reloadGrid },
                            { separator: true }
                        ],
                        searchitems: [
                            { display: "Name", name: "name", width: 180, sortable: true, align: "left" },
                            { display: "MobileNo", name: "code", width: 180, sortable: true, align: "left" }
                        ],
                        sortname: "id",
                        sortorder: "desc",
                        usepager: true,
                        singleSelect: true,
                        title: 'All Employees',
                        useRp: true,
                        rp: 15,
                        showTableToggleBtn: false,
                        height: getGridHeight(),
                        afterAjax: function (XMLHttpRequest, textStatus) {
                            afterAjaxError(XMLHttpRequest, textStatus);
                            showLoadingSpinner(false);
                        },
                        preProcess: onLoadInventoryListJSON
                    }
            );

    }

    function reloadGrid(com, grid) {
        if (com == 'Clear Results') {
            $('#flex1').flexOptions({ query: '' }).flexReload();
        }
    }

    function onLoadInventoryListJSON(data) {
        if (data.isError) {
            showError(data.message);
            worksListModel = null;
        } else {
            worksListModel = data;
        }
        return data;
    }


    function deleteWorks(com, grid) {
        var ids = $('.trSelected', grid);
        if (executePreConditionForDelete(ids) == false) {
            return;
        }
        showLoadingSpinner(true);
        var inventoryId = $(ids[ids.length - 1]).attr('id').replace('row', '');

        $.ajax({
            url: "${createLink(controller:'invItem', action: 'deleteWork')}?id=" + inventoryId,
            success: executePostConditionForDelete,
            complete: function (XMLHttpRequest, textStatus) {
                showLoadingSpinner(false);
            },
            dataType: 'json',
            type: 'post'
        });
    }

    function executePreConditionForDelete(ids) {
        var delCount = ids.length;
        if (delCount == 0) {
            showError("Please select a Works to delete");
            return false;
        }

        if (!confirm('Are you sure you want to delete the selected Works?')) {
            return false;
        }
        return true;
    }

    function executePostConditionForDelete(data) {
        if (data.deleted == true) {
            var selectedRow = null;
            $('.trSelected', $('#flex1')).each(function (e) {
                selectedRow = $(this).remove();
            });
            resetForm();
            $('#flex1').decreaseCount(1);
            showSuccess(data.message);
            worksListModel.total = parseInt(worksListModel.total) - 1;
            removeEntityFromGridRows(worksListModel, selectedRow);

        } else {
            showError(data.message);
        }
    }


    function selectWorks(com, grid) {

        var ids = $('.trSelected', grid);
        if (executePreConditionForEdit(ids) == false) {
            return;
        }

        resetForm();
        showLoadingSpinner(true);
        var inventoryId = $(ids[ids.length - 1]).attr('id').replace('row', '');
        $.ajax({
            url: "${createLink(controller:'invItem', action: 'selectWork')}?id="
                    + inventoryId,
            success: executePostConditionForEdit,
            complete: function (XMLHttpRequest, textStatus) {
                showLoadingSpinner(false);
            },
            dataType: 'json',
            type: 'post'
        });
    }


    function executePreConditionForEdit(ids) {
        if (ids.length == 0) {
            showError("Please select a Works to edit");
            return false;
        }
        return true;
    }

    function executePostConditionForEdit(data) {
        if (data.isError) {
            showError(data.message);
        } else {
            showWorks(data);
        }
    }

    function showWorks(data) {
        var entity = data.entity;
        $('#id').val(entity.id);
        $('#version').val(data.version);
        $('#name').val(entity.name);
        $('#unit').val(entity.unit);
        $('#code').val(entity.code);
        $('#create').attr('value', 'Update');
    }
</script>